package com.ordobill.remote.communication.resource.ftp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.net.SocketException;
import java.net.ConnectException;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import java.util.Properties;
import java.text.SimpleDateFormat;

import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPFile;
//import org.apache.commons.net.ftp.FTPSClient;
import org.apache.commons.net.ftp.FTPReply;
import com.ordobill.remote.communication.resource.ftp.NewFTPSClient;

/**
 * 
 * @author  Choi Jin Wook(A.K.A Brian Choi @ OrdoICT Office) / choijinwook84@gmail.com
 * @since   2012. 11. 26.
 * @version 0.1.0 (major.minor.fixtime)
 * TODO
 */
public class FSMain_MIG
{
    /**
     * 
     */
    public FSMain_MIG() {}
    
    /**
     * 
     */
    public static void main(String[] args) {
        
        NewFTPSClient client = new NewFTPSClient();
        
        client.setAutodetectUTF8(true);
        client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
        
        try {
            Properties properties = new Properties();

            properties.load(new FileInputStream("ftps.cfg"));
            properties.list(System.out);

            String KT_SVR_IP      = properties.getProperty("KT_SVR_IP"     );
            String KT_SVR_PORT    = properties.getProperty("KT_SVR_PORT"   );
            String KT_USR_ID      = properties.getProperty("KT_USR_ID"     );
            String KT_USR_PWD     = properties.getProperty("KT_USR_PWD"    );
            String KT_SVR_SRC_DIR = properties.getProperty("KT_SVR_SRC_DIR");
            String KT_SVR_TAR_DIR = properties.getProperty("KT_SVR_TAR_DIR");
            String KT_FILE_NAME   = properties.getProperty("KT_FILE_NAME"  );
            String NTELS_LOG      = properties.getProperty("NTELS_LOG"     );
            String BINARY_TYPE    = properties.getProperty("BINARY_TYPE"   );
            String ASCII_TYPE     = properties.getProperty("ASCII_TYPE"    );
            String FILE_SRC_DEL   = properties.getProperty("FILE_SRC_DEL"  );
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String sDate = sdf.format(new Date());

            Logger logger = FSMain_MIG.getLogger(NTELS_LOG+ "/KT_" + sDate + ".log");    
            /* Connection Example */
            FSMain_MIG.doPrintLogger(logger, System.out, "============================================== connect start!!");
            client.connect(KT_SVR_IP, Integer.valueOf(KT_SVR_PORT));

            if(!FTPReply.isPositiveCompletion(client.getReplyCode())){
                client.disconnect();
                FSMain_MIG.doPrintLogger(logger, System.out, "============================================== You couldn't be established connection with Server");
                System.exit(1);
            }
            /* Login Example */
            if(!client.login(KT_USR_ID, KT_USR_PWD)) 
            {
                FSMain_MIG.doPrintLogger(logger, System.out, "============================================== Login Failure!!");
                throw new SocketException("Login Failure");
            }
            
            if(client.getReplyCode()==230){
                FSMain_MIG.doPrintLogger(logger, System.out, "============================================== Login Succeed!!");
            }else{
                FSMain_MIG.doPrintLogger(logger, System.out, "============================================== Login Failure!!OB");
                throw new SocketException("Login Failure");
            }

            client.execPBSZ(0);
            client.execPROT("P");
            client.enterLocalPassiveMode();
            
            /*To decide download type
            To see ftps.cfg file*/
            if(BINARY_TYPE != null && ASCII_TYPE != null){
                
                if(BINARY_TYPE.equals("true")&&ASCII_TYPE.equals("false")){
                    
                    client.setFileType(FTP.BINARY_FILE_TYPE);//File Type Setting
                    client.setFileTransferMode(FTP.BINARY_FILE_TYPE); //Transport Formation Setting
                    
                }else if(BINARY_TYPE.equals("false")&&ASCII_TYPE.equals("true")){
                    
                    client.setFileType(FTP.ASCII_FILE_TYPE);
                    client.setFileTransferMode(FTP.ASCII_FILE_TYPE);
                    
                }
                
            }
            
            FSMain_MIG.doPrintLogger(logger, System.out, "============================================== Try to get file lists");
            client.pwd();
           
            Thread.sleep(1000); 
 
            //To Make First Time Error(Cheat) <<=522 SSL connection failed; session reuse required: see require_ssl_reuse option in vsftpd.conf man page
            client.listFiles();

            FSMain_MIG.doPrintLogger(logger, System.out, "============================================== " + sDate );

            File fChk = new File(KT_SVR_TAR_DIR);
            if(!fChk.isDirectory()) {   
                fChk.mkdirs();
            }
            
            fChk = new File(NTELS_LOG + sDate);
            if(!fChk.isDirectory()) {
                fChk.mkdirs();
            }
            
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            FSMain_MIG.doPrintLogger(logger, System.out, ">>>>>> START : " + sdf.format(new Date()) + " <<<<<<");
            
            //client.storeFile(KT_SVR_SRC_DIR + "/SCJM_FCDR4SVC_ID0001_T20120628010101.DAT",  new FileInputStream(KT_SVR_TAR_DIR + "/SCJM_FCDR4SVC_ID0001_T20120628010101.DAT")); 
            //client.storeFile(KT_SVR_SRC_DIR + "/SCJM_FCDR4SVC_ID0001_T20120628010101.FIN",  new FileInputStream(KT_SVR_TAR_DIR + "/SCJM_FCDR4SVC_ID0001_T20120628010101.FIN")); 
            
            FileOutputStream os;

            FSMain_MIG.doPrintLogger(logger, System.out, "============================================== TRY TO GET LIST OF FILES [" + KT_SVR_SRC_DIR + "]");
            
            for (FTPFile f : client.listFiles(KT_SVR_SRC_DIR)) {
                if(f.getType() == FTPFile.FILE_TYPE) {
                    FSMain_MIG.doPrintLogger(logger, System.out, "============================================== " + f.getName() + " = File");
                } else if(f.getType() == FTPFile.DIRECTORY_TYPE) {
                    FSMain_MIG.doPrintLogger(logger, System.out, "============================================== " + f.getName() + " = Directory");
                } else if(f.getType() == FTPFile.SYMBOLIC_LINK_TYPE) {
                    FSMain_MIG.doPrintLogger(logger, System.out, "============================================== " + f.getName() + " = Link");
                }
            }
            
            client.setControlKeepAliveTimeout(60000);
            
            FSMain_MIG.doPrintLogger(logger, System.out, "============================================== TRY TO DOWNLOAD FROM KT SERVER [" + KT_SVR_SRC_DIR + "]");

            for (FTPFile f : client.listFiles(KT_SVR_SRC_DIR + KT_FILE_NAME)) {
                if(f.getType() == FTPFile.FILE_TYPE) {
                    //String sDatFileNm = f.getName().replace(".FIN", ".DAT");
                    
                    FSMain_MIG.doPrintLogger(logger, System.out, "============================================== NOW DOWNLOADING! [" + f.getName() + "]");
                    os = new FileOutputStream(KT_SVR_TAR_DIR + "/" + f.getName());
                    client.retrieveFile(KT_SVR_SRC_DIR + "/" + f.getName(), os, f.getSize()); 
                    os.close();
                    
                    FSMain_MIG.doPrintLogger(logger, System.out, "============================================== DOWNLOAD COMPLETE! [" + f.getName() + "]");

                    if(FILE_SRC_DEL.equals("true")){
                        // Delete File
                        client.deleteFile(KT_SVR_SRC_DIR + "/" + f.getName());  // FIN File Delete
                        FSMain_MIG.doPrintLogger(logger, System.out, "============================================== DELETED : " + f.getName());
                    }
                } else if(f.getType() == FTPFile.DIRECTORY_TYPE) {
                    FSMain_MIG.doPrintLogger(logger, System.out, "============================================== " + f.getName() + " = Directory");
                } else if(f.getType() == FTPFile.SYMBOLIC_LINK_TYPE) {
                    FSMain_MIG.doPrintLogger(logger, System.out, "============================================== " + f.getName() + " = Link");
                }
            }
            
            FSMain_MIG.doPrintLogger(logger, System.out, "============================================== END : " + sdf.format(new Date()));

        }catch (Exception ftpsE){
            ftpsE.printStackTrace();
            System.out.println("Exception Message : " + ftpsE.getMessage() + ", Reply Code : " + client.getReplyCode() + ", Reply String : " + client.getReplyString());
        }finally{
            if(client.isConnected()) 
            {
                try
                {   
                    client.logout();
                    client.disconnect();
                }
                catch (IOException e) 
                {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * This is implementation instance of Logger
     * 
     * @param sLogFileName
     * @return Logger
     */
    public static Logger getLogger(String sLogFileName) {
        Logger logger = Logger.getLogger("Logging.KT.log");
        logger.setUseParentHandlers(false);
        
        FileHandler fileHandler = null;

        try {
            fileHandler = new FileHandler(sLogFileName, true);
        } catch(IOException e) {
            e.printStackTrace();
        }
        
        fileHandler.setFormatter(new SimpleFormatter());
        logger.addHandler(fileHandler);
        
        return logger;
    }
    
    /**
     * Print file and console sametime
     * 
     * @param logger
     * @param print
     * @param str
     */
    public static void doPrintLogger(Logger logger, PrintStream print, String str){
        logger.info(str);
        print.println(str);
    }
}